import {request, responseWrapper} from "../request";
import {hintError} from "./toast";
import {optimize} from "../core";

/**
 * 生成一个新的 modal框
 * @param {*} options
 * @param {function} success
 * @param {function} btn2Callback
 * @returns number
 */
function newModal(options, success, btn2Callback) {
	// 图库模板
	const PICTURE_TPL = `
<div class="layui-row layui-col-space10">
</div>
<div class="layui-laypage-wrapper" style="margin-top: 10px"></div>
`;
	return layer.open({
		id: options.id || "picture-dialog",
		area: ['530px', '450px'],
		title: '图片库',
		// type: 1,
		resize: false,
		tipsMore: true,
		content: PICTURE_TPL,
		btn: ['本地上传', '确定',],
		success: success,
		yes: () => false,
		btn3: btn2Callback
	});
}

/**
 * 生成url地址
 * @param {*} imageInfo
 * @return {*}
 */
function resolveUrl(imageInfo) {
	return imageInfo.url || imageInfo.path;
}

/**
 * 创建元素
 * @param {*} imageInfo
 * @return {*}
 */
function createItem(imageInfo) {
	const TPL = `
<div class="layui-col-sm2">
	<div class="uploader-wrapper">
		<img src="${resolveUrl(imageInfo)}" mode="aspectFill" class="uploader-image"  alt=""/>
	</div>
</div>
`;
	return $(TPL);
}

/**
 * 加载数据
 * @param {*} wrapper
 * @param {*} options
 * @return {Function}
 */
function loadDataFactory(wrapper, options) {
	const layPageWrapper = wrapper.next();
	const handler = function(page, limit = 20) {
		const url = options.listUrl;
		if (!url) {
			console.warn("not config picture url!");
			return;
		}

		return request.get(url, {
			page: page,
			limit: limit
		}, {
			tipsSuccessMsg: false
		}).then((res) => {
			wrapper.empty();
			res.data.reverse().forEach((item) => {
				wrapper.prepend(createItem(item));
			});

			//执行一个laypage实例
			layui.laypage.render({
				elem: layPageWrapper[0],
				count: res.total_count, //数据总数，从服务端得到
				limit: limit, // 分页条数
				curr: page,
				layout: ['prev', 'page', 'next', 'limit', 'count', 'refresh', 'skip',], // 布局
				theme: 2, //自定义主题
				jump: function(obj, first) {
					//首次不执行
					if (first) {
						return;
					}

					handler(obj.curr, obj.limit);
				}
			});
		});
	};
	return handler;
}

/**
 * 更新选中数量
 * @param {*} confirmBtn
 * @param {*} options
 * @param {array} choiceList
 * @return {Function}
 */
function updateChooseCountFactory(confirmBtn, options, choiceList) {
	const originText = confirmBtn.text();
	return function() {
		const max = options.multi ? options.max : 1;
		confirmBtn.text(`${originText}(${choiceList.length}/${max})`);
		confirmBtn.prop('disabled', choiceList.length);
	}
}

// 初始化选中图片事件
function initPicture(wrapper, options, choiceList) {
	return wrapper.on('click', '.uploader-wrapper', function() {
		const self = $(this), id = self.parent().data('id');

		//单选特殊处理
		if (!options.multi) {
			choiceList.splice(0, choiceList.length);
			wrapper.find('.uploader-selected').removeClass('uploader-selected');
			self.addClass('uploader-selected');

			choiceList.push({
				path: self.find('img').attr('src')
			});
		} else {
			//删除选中的元素
			if (self.hasClass('uploader-selected')) {
				const index = choiceList.findIndex(it => {
					return id === it.id
				});

				if (index !== -1) {
					choiceList.splice(index, 1);
				}

				self.removeClass('uploader-selected');
			} else {
				if (choiceList.length >= options.max) {
					hintError(`最多只能选择${options.max}张`);
					return;
				}

				choiceList.push({
					id: id,
					path: self.find('img').attr('src')
				});

				self.addClass('uploader-selected');
			}
		}
	});
}

/**
 * 初始化上传操作
 * @param {*} wrapper
 * @param {*} uploaderBtn
 * @param {*} options
 */
function initUpload(wrapper, uploaderBtn, options) {
	const url = options.uploadUrl;
	if (!url) {
		console.warn("upload url not config!");
		return;
	}

	layui.upload.render(optimize({
		elem: uploaderBtn[0],
		url: url,
		field: options.field || 'file', //设定文件域的字段名
		accept: 'image',//允许上传的文件类型
		size: options.size, //最大允许上传的文件大小
		acceptMime: options.acceptMime,//规定打开文件选择框时，筛选出的文件类型
		exts: options.exts, //允许上传的文件后缀
		multiple: true,//是否允许多文件上传
		// auto: false, //选择文件后不自动上传
		done: function(res) { //上传后的回调
			const response = responseWrapper(res);
			if (response.isSuccess) {
				wrapper.prepend(createItem(response.data));
			} else if (response.code === -1) { //未登录
				window.location.reload();
			} else {
				hintError(response.msg || "操作失败！");
			}
		},
		error: function() {
			hintError('上传服务器失败，请稍后再试~');
		},
	}));
}

/**
 * 生成新的配置数据
 * @param {*} options
 * @return {*}
 */
function newMergeConfig(options) {
	return Object.assign({}, uploadbox.defaults, options);
}

/**
 *
 * @param {{
 *     listUrl?:string,
 *     uploadUrl?:string,
 * }|*} options
 * @return {Promise<Array<string>>}
 */
export default function uploadbox(options = {}) {
	options = newMergeConfig(options);
	return new Promise(function(resolve) {
		// 选中的项
		const choiceList = [];

		// 弹出图片库
		newModal(options, function(dialog) {
			const wrapper = dialog.find('.layui-layer-content'),
				pictureWrapper = wrapper.children().eq(0),
				uploaderBtn = dialog.find('.layui-layer-btn0'),
				confirmBtn = dialog.find('.layui-layer-btn1');
			dialog.attr('type', 'page');

			// 生成函数
			const loadData = loadDataFactory(pictureWrapper, options);
			const updateChooseCount = updateChooseCountFactory(confirmBtn, options, choiceList);

			// 初始化相册
			initPicture(pictureWrapper, options, choiceList)
				.on('click', '.uploader-wrapper', function() {
					updateChooseCount();
					return false;
				});

			// 初始化上传操作
			initUpload(pictureWrapper, uploaderBtn, options);

			loadData(0);
			updateChooseCount();
		}, function(dialogId) {
			if (choiceList.length === 0) {
				hintError('请选择图片');
				return false;
			}

			layer.close(dialogId);

			resolve(choiceList.map(it => it.path));
		});
	});
};

uploadbox.defaults = {
	max: 1,
	size: 1024,
	field: 'image',
	acceptMime: 'image/*',
	exts: 'jpg|png|gif|bmp|jpeg'
};
